<?php

	/* Include all relevant files required */
	include_once("setup/setup.php");
	include_once("setup/mailSetup.php");
	include_once("mysql.php");
	include_once("configuration.php");
	include_once("process_forms.php");
	include_once("helperClasses.php");
	require_once("tcpdf_min/tcpdf.php");
	include_once("RenykalayaPDF.php");
	include_once("graphFunctions.php");
	include_once("phpmailer5/class.phpmailer.php");
	include_once("EmailAPI.php");
	include_once("Members.php");
	include_once("AdminActivities.php");
	//include_once("Pdf_Html.php");
	//include_once("jpGraphFunctions.php");
	
	//include_once("lib/phpmailer5/class.phpmailer.php");
	//require_once("lib/tcpdf_min/tcpdf.php");

	/* Set the default time zone so that the time stamps refer to Indian Standard Time */
	date_default_timezone_set("Asia/Kolkata");

	/* Function to get the current time stamp */
	function getCurrentDateTime() {
		$d = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
		return $d->format("Y-m-d H:i:s");
	}
	/* Function to get the next date */
	function getNextDate($date) {
		$date = date_create($date);
		date_add($date, date_interval_create_from_date_string('1 day'));
		return date_format($date,"Y-m-d");
	}

	/* Function to get the previous date */
	function getPreviousDate($date) {
		$date = date_create($date);
		date_add($date, date_interval_create_from_date_string('-1 day'));
		return date_format($date,"Y-m-d");
	}

	//function to set default error handeler
	function defaultErrorHandler($errno, $errstr, $errfile, $errline) {
		$errorMsg = "Error #{$errno} occured in {$errfile} on line # {$errline} with messahge : {$errstr} \n ";
		writeToLogFile($errorMsg);
		return true;
	}

	//function to write log files
	function writeToLogFile($msg,$sp='') {
		$date = date("Y-m-d");
		$fileName = "./logs/"."renukalaya-{$sp}".$date.".txt";
		$fh = fopen($fileName,"a");
		if($fh) {
				$tt = getCurrentDateTime();
				$eid = (defined('ENTITYID')) ? ENTITYID : "";
				fwrite($fh, "{$tt}\t{$eid}\t{$msg}\r\n");
				fclose($fh);
		}
	}

	//function to read log files
	class LogRead
	{
		private $filename = '';
	 
		function __construct($filename) 
		{
			$this->filename = $filename;
		}
	 
		public function tail($lines = 10) 
		{
			$data = '';
			$fp = fopen($this->filename, "r");
			$block = 4096;
			$max = filesize($this->filename);
	 
			for($len = 0; $len < $max; $len += $block){
				$seekSize = ($max - $len > $block) ? $block : $max - $len;
				fseek($fp, ($len + $seekSize) * -1, SEEK_END);
				$data = fread($fp, $seekSize) . $data;
	 
				if(substr_count($data, "\n") >= $lines + 1) 
				{
					/* Make sure that the last line ends with a '\n' */
					if(substr($data, strlen($data)-1, 1) !== "\n") {
						$data .= "\n";
					}
	 
					preg_match("!(.*?\n){". $lines ."}$!", $data, $match);
					fclose($fp);
					return $match[0];
				}
			}
			fclose($fp);
			return $data; 
		}
	}

	//Get content of current logs
	function getCurrentLogContent($currentPos=NULL) {
		$date = date("Y-m-d");
		$fileName = ".././logs/"."eetpl-motorTool-log-".$date.".txt";
		$log = new LogRead($fileName);
	 
		/* Get the last 40 lines */
		$lines = $log->tail(40);
		$lines = str_replace("\n","<br/>",$lines);
		
		$html = <<<EOT
			<div style="height:500px;overflow:scroll;">
				{$lines}
			</div>
EOT;
		return $html;
	}

	function dump_var($t,$v=null) {
		global $v_dump,$dFlag;
		if($dFlag) $v_dump[] = [$t,$v];
	}
	
	function _var_dump($data){
		echo "<pre>";
			var_dump($data);
		echo "</pre>";
	}
	
	function show_var_dump() {
		global $v_dump;
		if(count($v_dump)==0) return;
		foreach($v_dump as $v) {
			if(is_array($v[0])) {
				var_dump($v[0]);
			} else {
				echo $v[0]."<br/>";
			}
			echo "<pre>";
			var_dump($v[1]);
			echo "</pre><hr/>";
		}
	}


	function formatNumber($v,$noOfDec=2,$pad=null) {
		$num= sprintf("%.{$noOfDec}f",(float)$v);
		return $num;
		
		// this to be fixed latter
		if($num >= 100000){
			$num=$num/100000;
			$num=formatNumber($num);
			$num=$num."Lakh";
		}else if($num >= 1000){
			$num=$num/1000;
			$num=formatNumber($num);
			$num=$num."<b> K </b>";
		}
		
	}

	function formatDate($date,$format="d-m-Y") {
		if($date=="0000-00-00") return "-";
		$date = date_create($date);
		return date_format($date,$format);
	}


	function getAppBaseURL() {

		// Extract the request URL
		$base = $_SERVER['REQUEST_URI'];
		$parts = explode("/",$_SERVER['REQUEST_URI']);
		
		// Replace the file name with blank
		if($parts[count($parts)-1]!="") $base = str_replace($parts[count($parts)-1],"",$base);
		
		// Replace any mention of admin
		$base = str_replace("/admin","",$base);
		
		return  ((isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME']!="") ? $_SERVER['REQUEST_SCHEME'] : "http")."://".$_SERVER['SERVER_NAME'].$base;
	}
	
	function updateTable($tableName,$updateArray, $whereClause){
		$updateString="";
		foreach($updateArray as $k=>$v){
			$sep = $v == end($updateArray) ? "" :",";
			$updateString.="{$k} = '{$v}' ".$sep;
		}
		$sql=" UPDATE ".$tableName." SET ".$updateString." WHERE ".$whereClause;
		return executeUpdateQuery($sql);
	} 
	
	function validateDate($date){
		$d = DateTime::createFromFormat('Y-m-d', $date);
		return $d && $d->format('Y-m-d') == $date;
	}
?>
